package com.wxyzz.satserver.user.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wxyzz.common.core.entity.User;
import com.wxyzz.common.core.utils.JwtUtils;
import com.wxyzz.common.redis.utils.RedisUtils;
import com.wxyzz.satserver.user.dao.UserDao;
import com.wxyzz.satserver.user.param.LoginParam;
import com.wxyzz.satserver.user.service.LoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * --- 代码敲烂 月薪过万 ---
 *
 * @author zhouhaoyu
 * @date 2024/11/14
 * @desc
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserDao userDao;

    public String login(LoginParam loginParam ,HttpServletRequest  req) {
        User user = null;

        if (loginParam.getPhoneOrEmail().contains("@")){
            Pattern emailpattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
            // 判断邮箱格式
            if(!emailpattern.matcher(loginParam.getPhoneOrEmail()).matches()){
                throw new RuntimeException("邮箱格式错误");
            }
            user =userDao.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getEmail, loginParam.getPhoneOrEmail()));
        } else {
            Pattern phonepattern = Pattern.compile("^1[3-9]\\d{9}$");
            // 判断手机号格式
            if (!phonepattern.matcher(loginParam.getPhoneOrEmail()).matches()){
                throw new RuntimeException("手机号格式错误");
            }
            user = userDao.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getPhone, loginParam.getPhoneOrEmail()));

        }
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        // 使用md5加密密码
        String password = SecureUtil.md5(loginParam.getPassword());

        if (!user.getPassword().equals(password)){
            throw new RuntimeException("密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        String token = JwtUtils.createJwt(map);
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);

        return token;
    }
}
